import Vue from 'vue'
import App from './App.vue'
import router from './router'
import './plugins/element.js'
import './assets/global.css'
import {formatDict} from './utils/his-utils'
// 注册mavon-editor组件
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
Vue.use(mavonEditor);

import ax from 'axios';
const axios = ax.create({
  baseURL:'http://localhost:86'
})

//将axios注册为全局变量
Vue.prototype.$axios=axios;

//将封装的字典解析注册为全局变量
Vue.prototype.formatDict=formatDict

//--------------------------------xgz---------------------------------------------
import moment from 'moment'
import {selectDictLabel, addDateRange, handleTree, getAge, getCurrentTimeType} from './utils/his-utils'
Vue.prototype.selectDictLabel = selectDictLabel
Vue.prototype.addDateRange = addDateRange
Vue.prototype.handleTree = handleTree // 挂载全局的构造树的JSON的方法
Vue.prototype.getAge = getAge// 挂载全局的根据出生年月日计算年龄的方法
Vue.prototype.getCurrentTimeType = getCurrentTimeType// 挂载全局计算时段的方法
Vue.prototype.moment = moment
//--------------------------------xgz---------------------------------------------

Vue.config.productionTip = false

//设置前置路由守卫 to：跳转的路径  from：从哪里来 next 下一步
router.beforeEach((to,from,next)=>{
  //获取跳转的路径
  let path = to.path;
  if(path==='/login'||path==='/'){
    return next();
  }
  //判断是否登录
  let token = sessionStorage.getItem("token");
  if(token){
    return next();
  }
  return next("/login");
})

//设置请求拦截器（每次请求在请求头里面存放token信息）
axios.interceptors.request.use(config=>{
  let token = sessionStorage.getItem("token")
  if(token){
    config.headers.token=token;
  }
  return config;
})

//设置响应拦截器
axios.interceptors.response.use(response=>{
  if(response.data.code===200){
    return response;
  }else if(response.data.code===500){
    Vue.prototype.$message.error("服务器错误")
    return Promise.reject(new Error()) //拒绝访问
  }else if(response.data.code===403){
    Vue.prototype.$message.error("权限不足")
    return Promise.reject(new Error())
  }else if(response.data.code===401){
    Vue.prototype.$message.error("登录失效")
    vm.$router.push("/login")
    return Promise.reject(new Error())
  }else {
    Vue.prototype.$message.error("未登录")
    return Promise.reject(new Error())
  }
})

var vm = new Vue({
  router,
  render: h => h(App)
}).$mount('#app')
